<?php 

class Event_CommentPreSave extends Crud_Event_Handler 
{
	protected $_type = 'preSave';
	
	/**
	 * Run handler with options array.
	 * 
	 * @param OrdersRow $row
	 * @return void
	 */
	public function run($row)
	{
		$rowValue = $row->getAdminAnswer();
		/*$currentValue = 'Ответ на комментарий к <a href="http://'.$_SERVER['SERVER_NAME'].'/product/index/id/'.$row->getItemId().'/">товару</a><br>';
		$currentValue .= $this->_getParam("admin_answer");
		$currentValue .= '<p>------------------------------------------</p>';
		$currentValue .= '<p>Теперь ваш малыш будет действительно всегда сухим, ведь в интернет-магазине "Детский Мир" начались продажи подгузников <a href="http://detmir.ru/catalog/index/name/podguzniki/" target="_blank">ведущих мировых марок</a></p>';
		*/
		$link = $_SERVER['SERVER_NAME'].'/product/index/id/'.$row->getItemId().'/';
	
		if($this->_getParam("is_replied")){

			$commnetRow = CommentPeer::getInstance()->update(array("admin_answer" => $this->_getParam("admin_answer")), 'id = '.$row->getId());
			
			$ProductRows = ProductPeer::getInstance()->findById($row->getItemId());
			$ProfileRows = ProfilePeer::getInstance()->findById($row->getProfileId());
			$to_mail = $row->getUnregUserEmail();
			
			//$to_mail = "vdiomidov@mail.ru";
			if(!$to_mail)
					$to_mail = $ProfileRows[0]["email"];	

			$mail = MailService::getInstance()->getMailTemplate('comment_reply');
			$text = $mail["text"];
			$text = str_replace("[LINK]",$link,$text);
			$text = str_replace("[ANSWERTEXT]",$this->_getParam("admin_answer"),$text);
			
			$text = str_replace("[PRODUCT]",$ProductRows[0]["name"],$text);
			
			$unsubscribe="http://".Config::getInstance()->default->hostname."/subscribe/off/type/general/email/".$to_mail."/code/".$ProfileRows[0]['token']."/";			
			$text = str_replace("[UNSUBSCRIBE]",$unsubscribe,$text);
			
			
			$zmail = new Zend_Mail('UTF-8');
			$zmail->setSubject($mail["subject"]);
			$zmail->setBodyHtml($text);
			$zmail->setFrom($mail["from_email"],$mail["from_name"]);		  
			$zmail->addTo($to_mail);
			$zmail->send();

			
		}
		
	}
	
}
